//
//  MyQRCodeViewController.swift
//  weibopush
//
//  Created by 龚欣 on 15/6/29.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage
class MyQRCodeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
       
        view.backgroundColor = UIColor.whiteColor()
        
        iconView.ff_AlignInner(ff_AlignType.CenterCenter, referView: view, size: CGSizeMake(200, 200), offset: CGPointZero)
        
        iconView.image = generateQRCodeImage()
    }
    
    override func loadView() {
       view = UIView()
        
       view.addSubview(iconView)
        
    }
    
    private func generateQRCodeImage() -> UIImage{
        //1 建立一个二维码滤镜
        let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
        //2 设置默认初始值
        qrFilter.setDefaults()
        //3 通过KVC给二维码赋值
        qrFilter.setValue("John Snow You Know Nothing".dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
        //取出图片
        let ciImage = qrFilter.outputImage
        let transform = CGAffineTransformMakeScale(10, 10)
        let scaleCIImage = ciImage.imageByApplyingTransform(transform)
        print(UIImage(CIImage: scaleCIImage).size)
        
        
        return insertAvatarImage(UIImage(CIImage: scaleCIImage), avatar: avatarImageView.image!)
    }
    
    private func insertAvatarImage(image : UIImage,avatar : UIImage) -> UIImage{
        
        UIGraphicsBeginImageContext(image.size)
        
        image.drawInRect(CGRect(origin: CGPointZero, size: image.size))
        let w : CGFloat = 70
        let x : CGFloat = (image.size.width - w ) * 0.5
        let y : CGFloat = (image.size.height - w) * 0.5
        let rect = CGRect(x: x, y: y, width: w, height: w)
        avatar.drawInRect(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
    
        return image
    }

    lazy var iconView : UIImageView = UIImageView()
    lazy var avatarImageView : UIImageView = {
        let avatarV = UIImageView()
        let URL = NSURL(string: (sharedAccount?.avatar_large)!)!
        avatarV.sd_setImageWithURL(URL)
        
        return avatarV
        }()
}
